<?php
namespace MyContent\Model;

use Zend\Db\TableGateway\TableGateway;

class ContentTable  
{
	protected $tableGateway;
	
	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;		
	}
	
	public function fetchAll()
	{
		$resultSet = $this->tableGateway->select();
		return $resultSet;
	}
	
	public function getContent($id)
	{
		$id = (int) $id;
		$rowset = $this->tableGateway->select(array('id' => $id));
		$row = $rowset->current();
		if(!$row)
		{
			throw new \Exception("Could not find row $id");
		}
		return $row;
	}
	
	public function getLastId(){
		return $this->tableGateway->getLastInsertValue();
	}
	
	public function saveContent(Content $Content)
	{
		$data = array(
				'link' => $Content->link,
				'type' => $Content->type,
				'date' => $Content->date,
				'desc' => $Content->desc,
				);
		
		$id = (int) $Content->id;
		
		if($id == 0)
		{
			$this->tableGateway->insert($data);
			$id = $this->tableGateway->getLastInsertValue();
		}else 
		{
			if($this->getContent($id))
			{
				$this->tableGateway->update($data,array('id' => $id));
			}else
				{
					throw new \Exception('Content does not exist');
				}
		}
		return $id;
	}
	
	public function deleteContent($id)
	{
		$this->tableGateway->delete(array('id' => (int)$id));
	}
}